package com.beemans.topon.views

import android.content.Context
import android.util.AttributeSet
import androidx.annotation.CallSuper
import androidx.lifecycle.LifecycleOwner
import com.anythink.nativead.api.ATNativeAdView
import com.beemans.topon.ads.INativeSelfRender
import com.beemans.topon.ads.TpNativeAd

/**
 * @author tiamosu
 * @date 2021/5/21.
 */
open class NativeAdLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ATNativeAdView(context, attrs, defStyleAttr) {
    private val exposureHelper by lazy { ExposureHelper() }

    var adLoader: TpNativeAd.TpNativeAdLoader? = null
        private set

    /**
     * 视图是否处于屏幕可见
     */
    val isLocalVisible: Boolean
        get() = exposureHelper.isLocalVisible

    init {
        exposureHelper.init(apply { }) { isVisible ->
            onAdVisible(isVisible)
        }
    }

    /**
     * 设置广告加载器
     */
    fun setAdLoader(adLoader: TpNativeAd.TpNativeAdLoader?) {
        this.adLoader = adLoader
    }

    /**
     * 加载广告
     */
    fun loadAd(
        owner: LifecycleOwner,
        config: TpNativeAd.TpNativeAdConfig,
        nativeSelfRender: INativeSelfRender? = null,
        nativeAdCallback: (TpNativeAd.TpNativeAdCallback.() -> Unit)? = null
    ) {
        if (adLoader == null) {
            adLoader = TpNativeAd.TpNativeAdLoader(
                owner = owner,
                config = config,
                flContainer = this,
                nativeSelfRender = nativeSelfRender,
                nativeAdCallback = nativeAdCallback
            )
        }
        adLoader?.let(TpNativeAd::start)
    }

    /**
     * 释放广告
     */
    fun onAdRelease() {
        adLoader?.onAdRelease()
        adLoader = null
    }

    @CallSuper
    open fun onAdVisible(isVisible: Boolean) {
        adLoader?.onAdVisible(isVisible)
    }
}